package convert;

import com.alibaba.fastjson.JSON;
import exception.PackConvertException;

import java.nio.ByteBuffer;

/**
 * Create Time: 2018年01月26日 13:35
 *
 * @author fin
 */
public class ClampPackageConverter extends AbstractPackageConverter {

    public Transferable getPackage(byte[] bytes) throws PackConvertException{
        ClampPackage protocol = new ClampPackage();

        int length = 0;
        byte [] content = new byte[4];
        System.arraycopy(bytes,length,content,0,4);
        int version = bytes2int(content);
        if (version <= 0){
            throw new PackConvertException("Wrong Version : "+version + " !");
        }
        protocol.setVersion(version);
        length+=4;

        System.arraycopy(bytes,length,content,0,4);
        int action = bytes2int(content);
        if (action <= 0){
            throw new PackConvertException("Wrong Action : "+action + " !");
        }
        protocol.setAction(action);
        length +=4;

        content = new byte[8];
        System.arraycopy(bytes,length,content,0,8);
        long size = bytes2long(content);
        if (size < 16){
            throw new PackConvertException("Wrong Size : "+size + " !");
        }
        protocol.setSize(size);
        length +=8;

        /* body is not null **/
        if (bytes.length > length){
            content = new byte[bytes.length - length];
            System.arraycopy(bytes,length,content,0,content.length);
            String json = new String(content);
            protocol.setBody(JSON.parseObject(json));
        }
        else protocol.setBody(null);

        return protocol;
    }

    public byte[] getBytes(Transferable transferable) throws PackConvertException {
        ClampPackage clampPackage = null;
        // 确保类型正确
        if(transferable instanceof ClampPackage)
            clampPackage = transferable.cast(ClampPackage.class);
        else
            throw new PackConvertException("不支持的协议格式");

        // 包解析
        return getBytes(clampPackage);
    }

    private byte[] getBytes(ClampPackage clampPackage){
        byte [] json = clampPackage.getBody().toString().getBytes();
        byte [] res = new byte[4 + 4 + 8 + json.length];

        byte [] v = int2bytes(clampPackage.getVersion());
        System.arraycopy(v,0,res,0,4);
        int length = INT_LENGTH ;

        byte [] a  = int2bytes(clampPackage.getAction());
        System.arraycopy(a,0,res,length,4);
        length += INT_LENGTH;

        byte [] size = long2bytes((long)res.length);
        System.arraycopy(size,0,res,length,8);
        length += LONG_LENGTH;

        System.arraycopy(json,0,res,length,json.length);

        return res;
    }


}
